﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.Tool.Forms;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;

namespace ERP_RORZE_TOOL.Tool.UserControls
{
	public partial class ucTool : DevExpress.XtraEditors.XtraUserControl
	{
		private int index = 0;
		public int _action = 1;
        ToolHelper helper=new ToolHelper(new Tools());

        DXPopupMenu menu;

		#region Handle Methods

		public ucTool()
		{
            InitializeComponent();
		    InitPopupMenu();

            BindDatatoGrid();
            gridView1.BestFitColumns();
		    this.dropbtExport.DropDownControl = menu;
		}

		private void btAddNew_Click_1(object sender, EventArgs e)
		{
			AddNew();
		}

		private void btEdit_Click_1(object sender, EventArgs e)
		{
			EditRow();
		}

		private void btDelete_Click_1(object sender, EventArgs e)
		{
			DeleteRows();
		}

		private void gridView1_CustomDrawEmptyForeground_1(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
		{
			if(gridView1.RowCount != 0)
				return;

			StringFormat drawFormat = new StringFormat();

			drawFormat.Alignment = drawFormat.LineAlignment = StringAlignment.Center;

			e.Graphics.DrawString("No items exist in this view", e.Appearance.Font, SystemBrushes.ControlDark, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), drawFormat);

		}

		private void gridView1_DoubleClick_1(object sender, EventArgs e)
		{
			var gridView = (GridView)sender;
			var point = gridView.GridControl.PointToClient(Control.MousePosition);

			DoDoubleClick(gridView, point);
		}

		private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
		{
			AddNew();
		}

		private void editToolStripMenuItem_Click(object sender, EventArgs e)
		{
			EditRow();
		}

		private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
		{
			DeleteRows();
		}
		#endregion

		public void BindDatatoGrid()
		{
			ToolHelper helper = new ToolHelper(new Tools());
			DataTable dt = helper.GetAll();

			gridControl1.DataSource = dt;
			Utilities.GridUtil.SelectRow(gridView1, index, _action);
		}

		private void DoDoubleClick(GridView v, Point p)
		{
			_action = 1;
			index = gridView1.FocusedRowHandle;
			var info = v.CalcHitInfo(p);
			if(info.InRow || info.InRowCell)
			{
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);
				string toolId = row[0][ToolConstants.Entities.Tool.FieldName.ToolID].ToString();
			    helper.ValueObject.ToolID = toolId;
                helper.LoadOne();

				frm_ToolEdit fr = new frm_ToolEdit(this);
				fr.ToolId = helper.ValueObject.ToolID;
                fr.ToolName = helper.ValueObject.ToolName;
                fr.MakerToolName = helper.ValueObject.MakerToolName;
                fr.Price = helper.ValueObject.Price;
			    fr.SafeQty = helper.ValueObject.SafeQty;
				fr.FrequencyId = helper.ValueObject.FrequencyID;
				fr.ToolGroupId = helper.ValueObject.ToolGroupID;
				fr.MakerId = helper.ValueObject.MakerID;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
			}
		}

		private void DeleteRows()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				var row = new DataRow[gridView1.SelectedRowsCount];
				var toolId = new string[gridView1.SelectedRowsCount];

				for(int i=0; i< gridView1.SelectedRowsCount; i++)
				{
					row[i]= gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
					toolId[i] = row[i][ToolConstants.Entities.Tool.FieldName.ToolID].ToString();
				}


				if(MessageBox.Show(ToolConstants.Message.DeleteQuestion, ToolConstants.Form.MessageBox.Warning,
								MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
				{
					ToolHelper helper = new ToolHelper(new Tools());
					for(int i = 0; i < toolId.Length; i++)
					{
						helper.ValueObject.ToolID = toolId[i];
						if(helper.Delete() >0)
						{
							_action = 2;
						}
						else
						{
							MessageBox.Show(ToolConstants.Message.DeleteFailed, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					}
                    BindDatatoGrid();


				}
			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void EditRow()
		{
			if(gridView1.SelectedRowsCount >0)
			{
				frm_ToolEdit fr = new frm_ToolEdit(this);
				var row = new DataRow[gridView1.SelectedRowsCount];
				row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

				index = gridView1.FocusedRowHandle;
				_action = 1;

				string toolId = row[0][ToolConstants.Entities.Tool.FieldName.ToolID].ToString();
                helper.ValueObject.ToolID = toolId;
                helper.LoadOne();

                fr.ToolId = helper.ValueObject.ToolID;
                fr.ToolName = helper.ValueObject.ToolName;
                fr.MakerToolName = helper.ValueObject.MakerToolName;
                fr.Price = helper.ValueObject.Price;
                fr.SafeQty = helper.ValueObject.SafeQty;
                fr.FrequencyId = helper.ValueObject.FrequencyID;
                fr.ToolGroupId = helper.ValueObject.ToolGroupID;
                fr.MakerId = helper.ValueObject.MakerID;

                fr.StartPosition = FormStartPosition.CenterParent;
				fr.ShowDialog();
			}
			else
			{
				MessageBox.Show(ToolConstants.Message.TableIsNull, ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
								MessageBoxIcon.Information);
			}
		}

		private void AddNew()
		{
			Cursor.Current = Cursors.WaitCursor;
			Form fr = new frm_ToolAdd(this);
            fr.StartPosition = FormStartPosition.CenterParent;
			fr.ShowDialog();
			Cursor.Current = Cursors.Default;

		}

        private void btRefresh_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            BindDatatoGrid();
            Cursor.Current = Cursors.Default;
        }

        private void gridControl1_ProcessGridKey(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteRows();
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            FileDialog fileDialog = new OpenFileDialog();
            fileDialog.Filter = ToolConstants.Configuration.FilterFile.Excel;

            int rowCount = 0;

            INISettings iniSettings = new INISettings();
            string connectString = iniSettings.SQLConnectionString;
            OleDbConnection connection = new OleDbConnection();
            OleDbCommand command = null;

            // Create DbDataReader to Data Worksheet
            DbDataReader dr = null;

            // Bulk Copy to SQL Server 
            SqlBulkCopy bulkInsert = new SqlBulkCopy(connectString);

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {

                try
                {
                    string path = fileDialog.FileName;

                    // Connection String to Excel Workbook
                    string excelConnectionString =
                        string.Format(
                            "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;Persist Security Info=False",
                            path);

                    connection.ConnectionString = excelConnectionString;
                    connection.Open();

                    command = new OleDbCommand("select  COUNT(*) from [Sheet1$]", connection);
                    rowCount = (int)command.ExecuteScalar();

                    command = new OleDbCommand("select * from [Sheet1$]", connection);
                    dr = command.ExecuteReader();

                    bulkInsert.DestinationTableName = ToolConstants.DatabaseName + ".[dbo].[" + ToolConstants.Entities.Tool.Name + "]";

                    SqlBulkCopyColumnMapping toolId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.ToolID, ToolConstants.Entities.Tool.FieldName.ToolID);
                    bulkInsert.ColumnMappings.Add(toolId);

                    SqlBulkCopyColumnMapping toolName = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.ToolName, ToolConstants.Entities.Tool.FieldName.ToolName);
                    bulkInsert.ColumnMappings.Add(toolName);

                    SqlBulkCopyColumnMapping makerToolName = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.MakerToolName, ToolConstants.Entities.Tool.FieldName.MakerToolName);
                    bulkInsert.ColumnMappings.Add(makerToolName);

                    SqlBulkCopyColumnMapping price = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.Price, ToolConstants.Entities.Tool.FieldName.Price);
                    bulkInsert.ColumnMappings.Add(price);

                    SqlBulkCopyColumnMapping frequencyId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.FrequencyID, ToolConstants.Entities.Tool.FieldName.FrequencyID);
                    bulkInsert.ColumnMappings.Add(frequencyId);

                    SqlBulkCopyColumnMapping toolGroupId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.ToolGroupID, ToolConstants.Entities.Tool.FieldName.ToolGroupID);
                    bulkInsert.ColumnMappings.Add(toolGroupId);

                    SqlBulkCopyColumnMapping safeQty = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.SafeQty, ToolConstants.Entities.Tool.FieldName.SafeQty);
                    bulkInsert.ColumnMappings.Add(safeQty);

                    SqlBulkCopyColumnMapping makerId = new SqlBulkCopyColumnMapping(ToolConstants.Entities.Tool.FieldName.MakerID, ToolConstants.Entities.Tool.FieldName.MakerID);
                    bulkInsert.ColumnMappings.Add(makerId);

                    Cursor.Current = Cursors.WaitCursor;
                    bulkInsert.WriteToServer(dr);
                    Cursor.Current = Cursors.Default;

                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.Return, string.Format(ToolConstants.Message.ImportSuccessfullyLog, rowCount.ToString()));
                    DialogResult message = MessageBox.Show(string.Format(ToolConstants.Message.ImportSuccessfully, rowCount.ToString()),
                                                           ToolConstants.Form.MessageBox.Message,
                                                           MessageBoxButtons.OKCancel);
                    if (message == DialogResult.OK)
                    {
                        BindDatatoGrid();
                    }

                }
                catch (Exception exception)
                {
                    Utilities.CreateLogFile(ToolConstants.Configuration.LogFileName.Return, string.Format(ToolConstants.Message.ImportFailedLog, exception.Message));
                    MessageBox.Show(exception.Message);
                }
                finally
                {
                    if (connection != null && connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }

        protected virtual void InitPopupMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem("Export all", new EventHandler(OnItemClickExportAll), null, null, null, null));
            menu.Items.Add(new DXMenuItem("Export selected row(s)", new EventHandler(OnItemClickExportRows), null, null, null, null));

        }
        void OnItemClickExportAll(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(gridView1, 1, true);
        }
        void OnItemClickExportRows(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(gridView1, 0, true);
        }

	}
}
